#include <stdio.h>

#define STACK_MAX_LEN 50

#define BOOL int
#define TRUE 1
#define FALSE 0

struct char_stack
{
	char stack[STACK_MAX_LEN];
	int top;
};


/*
*	输入参数 字符串s指针 [low, high)检测括号是否匹配的范围
*	返回值 -1 括号类型不匹配
			0 左括号多了
			1 匹配
			2 右括号多了
*/
int brance_match(char * s, int low, int high);
BOOL is_left_brance(char ch);
BOOL is_right_brance(char ch);
BOOL left_right_match(char ch1, char ch2);
void push(struct char_stack * p, char ch);
void pop(struct char_stack * p);

int main(void)
{
	char c[100];
	int i;
	int op = 1;

	while (op == 1)
	{
		printf("input: (input \"exit\" to exit)\n");
		scanf("%s", c);
		for (i = 0; c[i] != '\0'; ++i)
			;
		if (c[0] == 'e' && c[1] == 'x' && c[2] == 'i' &&
			c[3] == 't' && c[4] == '\0')
			return 0;

		switch(brance_match(c, 0, i))
		{
			case -1:{
				printf("diffierent type!\n");
				break;
			}
			case 0: {
				printf("too much left brance\n");
				break;
			}
			case 1: {
				printf("ok!\n");
				break;
			}
			case 2: {
				printf("too much right brance\n");
				break;
			}
			default: break;
		}
	}


	return 0;
}

int brance_match(char * pchar, int low, int high)
{
	struct char_stack s;
	s.top = 0;

	int i;

	for (i = low; i < high; ++i)
	{
		if (is_left_brance(pchar[i]))
		{
			push(&s, pchar[i]);
		}
		else if (is_right_brance(pchar[i]))
		{
			if (s.top <= 0)
				return 2;	//右括号多了
			else if (left_right_match(s.stack[s.top], pchar[i]))
			{
				pop(&s);
			}
			else
			{
				return -1;	//括号类型不匹配
			}
		}
		else
			continue;
	}
	if (s.top == 0)
		return 1;	//匹配
	else
		return 0;	//左括号多了
}

BOOL is_left_brance(char ch)
{
	if (ch == '(' || ch == '[' || ch == '{')
		return TRUE;
	else
		return FALSE;
}
BOOL is_right_brance(char ch)
{
	if (ch == ')' || ch == ']' || ch == '}')
		return TRUE;
	else
		return FALSE;
}
BOOL left_right_match(char ch1, char ch2)
{
	if ((ch1 == '(' && ch2 == ')') ||
		(ch1 == '[' && ch2 == ']') ||
		(ch1 == '{' && ch2 == '}')	)
		return TRUE;
	else
		return FALSE;
}

void push(struct char_stack * p, char ch)
{
	p->stack[++p->top] = ch;
}
void pop(struct char_stack * p)
{
	--p->top;
}